package com.dlc.shop.common.serializer.json;

import cn.hutool.core.collection.CollectionUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.dlc.shop.common.config.SensitiveWordConfig;
import com.dlc.shop.common.handler.SensitiveHandler;
import com.dlc.shop.common.util.HttpContextUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.util.Objects;
import java.util.Set;

/**
 * @author lanhai
 */
@Component
@Slf4j
public class SensitiveJsonSerializer extends JsonSerializer<Object> {

    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private SensitiveHandler sensitiveHandler;


    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        HttpServletRequest httpServletRequest = HttpContextUtils.getHttpServletRequest();
        if (Objects.isNull(httpServletRequest)) {
            gen.writeObject(value);
            return;
        }
        String requestUrl = httpServletRequest.getRequestURI();
        Set<String> sensitiveWhiteSet = SensitiveWordConfig.getSensitiveWhiteSet();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        if (CollectionUtil.isNotEmpty(sensitiveWhiteSet)){
            for (String sensitiveUrl : sensitiveWhiteSet) {
                if (antPathMatcher.match(sensitiveUrl,requestUrl)){
                    gen.writeObject(value);
                    return;
                }
            }
        }
        if (Objects.isNull(value)) {
            return;
        }
        try {
            String jsonData = objectMapper.writeValueAsString(value);
            String sensitiveText = sensitiveHandler.replaceSensitiveWord(jsonData, SensitiveHandler.minMatchType, "*");

            gen.writeObject(objectMapper.readValue(sensitiveText,value.getClass()));
        } catch (Exception e) {
            log.error("敏感词替换错误：", e);
        }
    }
}
